<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { PlusColumn } from 'plus-pro-components'

import { SubmitBtn } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['getSaleAttribute'])
const { createMessage } = useMessage()
const visible = defineModel<boolean>('visible', { required: true })
const saleAttributeName = defineModel<string>('saleAttributeName', { required: true })
const formRef = ref()
type Istate = {
    id?: string
    value?: string
}

const initialState = {
    id: '',
    value: '',
}
const state = ref<Istate>(cloneDeep(initialState))

const columns: PlusColumn[] = [
    {
        label: '属性名',
        prop: 'name',
    },
    {
        label: '属性值',
        prop: 'value',
    },
]

function validateValue(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入属性值'))
    }
    if (pattern.test(value))
        callback(new Error('属性值不允许输入空格'))

    else
        callback()
}

const rules = {
    value: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateValue,
        },
    ],
}

function cancel() {
    visible.value = false
}
function reset() {
    visible.value = false
    formRef.value.formInstance.resetFields()
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        state.value.id = state.value.value
        delete state.value.name
        emits('getSaleAttribute', { ...state.value, flag: false, isCustomerAttribute: 1 })
        visible.value = false
        createMessage.success('添加成功')
    }
}
</script>

<template>
    <PlusDialog v-model="visible"
                title="添加属性值"
                width="400"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-name>
                {{ saleAttributeName }}
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style scoped lang='scss'>
</style>
